<template>
  <el-dialog
    width="40%"
    append-to-body 
    top="15vh"
    title="导入出库单"
    :close-on-click-modal="false"
    :visible.sync="show"
  >
    <el-form class="import-delivery">
      <el-form-item>
        <template slot="label">
          <div class="import-label">
            <label>请先下载出库单：</label>
            <span class="tip">（填写完成后上传）</span>
          </div>
        </template>
        <el-link @click="onDown" :underline="false">下载出库单</el-link>
      </el-form-item>
      <el-form-item label="上传选择：">
        <el-row class="form-items">
          <el-col :span="12">
            <el-select 
              v-model="postData.deliveryType"
              placeholder="出库方式"
              :clearable="false"
            >
              <template v-for="item in deliveryTypes">
                <el-option 
                  :key="item.id" 
                  :label="item.text" 
                  :value="item.id">
                </el-option>
              </template>
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-select 
              v-model="postData.collectDeptId"
              @change="onChangeDept"
              placeholder="领用科室"
              clearable
            >
              <template v-for="item in collectDepts">
                <el-option 
                  :key="item.id" 
                  :label="item.text" 
                  :value="item.id">
                </el-option>
              </template>
            </el-select>
          </el-col>
        </el-row>
        <el-row class="form-items">
          <el-col :span="12">
            <el-select 
              v-model="postData.collectUseId"
              @change="onChangeUser"
              placeholder="领用人"
              clearable
            >
              <template v-for="item in users">
                <el-option 
                  :key="item.id" 
                  :label="item.text" 
                  :value="item.id">
                </el-option>
              </template>
            </el-select>
          </el-col>
          <el-col :span="12">
            <el-input v-model="postData.remark" placeholder="备注"/>
          </el-col>
        </el-row>
        <el-row class="tip">必选项，请上传前选择</el-row>
      </el-form-item>
      <el-form-item label="上传文件：">
        <el-upload
          ref="upload"
          class="upload-demo"
          name="file"
          :action="uploadUrl"
          :auto-upload="false"
          :headers="headers"
          :on-success="onSuccess"
          :on-error="onError"
          :before-upload="onBeforeUpload"
          :data="postData"
          drag
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此区域</div>
          <el-button size="small">上传文件</el-button>
          <div class="upload-hint" slot="tip">
            <i class="el-icon-warning-outline"></i>
            文件仅支持xls/xlsx格式的文件
          </div>
        </el-upload>
      </el-form-item>
      <div class="dialog-footer">
        <el-button @click="show = false">关闭</el-button>
        <el-button type="primary" :loading="loading" @click="onSubmit">提交</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
import { outTemplate, getCollectUses, getDepartments } from '@/api/storageRoom/drugDelivery';
import { getToken } from '@/utils/auth';
import { mapGetters } from "vuex";

export default {
  name: "importDelivery",
  inheritAttrs: false,
  data() {
    let baseUrl = process.env.VUE_APP_BASE_API;
    return {
      headers: {
        Authorization: getToken()
      },
      postData: {
        collectDeptId: null,
        collectDeptName: null,
        collectUseId: null,
        collectUseName: null,
        deliveryType: 2,
        remark: null,
      },
      collectDepts: [],
      users: [],
      uploadUrl: baseUrl + "/drugdelivery/inTemplate",
      show: false,
      loading: false,
      pharmacyId: null,
    }
  },
  computed: {
    ...mapGetters(["deliveryTypes"]),
    downUrl() {
      let baseUrl = process.env.VUE_APP_BASE_API;
      return baseUrl + "/drugWareHousing/outTemplate";
    }
  },
  created() {
    this.$store.dispatch("GetInfo").then(res => {
      this.pharmacyId = res.pharmacyId;
    });
    this._getDepartments();
    this._getCollectUses();
  },
  methods: {
    onSubmit() {
      if(!this.postData.collectDeptId) {
        this.$message.error('请选择领用科室!');
        return;
      }
      if(!this.postData.collectUseId) {
        this.$message.error('请选择领用人!');
        return;
      }
      if(this.$refs.upload.uploadFiles.length === 0) {
        this.$message.error('请选择文件!');
        return;
      }
      this.loading = true;
      this.$refs.upload.submit();
    },
    onBeforeUpload(file) {
      let isPic =
        file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      if (!isPic) {
        this.$message.error('上传文件只能是xls、xlsx格式!');
        this.loading = false;
        return false;
      }
      return isPic;
    },
    onSuccess() {
      this.$notify({
        title: "导入成功",
        type: "success"
      });
      this.loading = false;
      this.$refs.upload.clearFiles();
      this.$emit("success");
      this.show = false;
      this.collectDeptId = null;
      this.collectDeptName = null;
      this.collectUseId = null;
      this.collectUseName = null;
      this.deliveryType = null;
    },
    onError(error) {
      console.error(error);
      this.loading = false;
      let msg = '请求失败';
      if(error.message.indexOf("{\"status") === 0) {
        msg = JSON.parse(error.message).message;
      }
      this.$notify({
        title: msg,
        type: 'error'
      });
    },
    onDown() {
      outTemplate();
    },
    onChangeDept() {
      let id = this.postData.collectDeptId;
      let depts = this.collectDepts.filter(item => {
        return item.id === id; 
      });
      this.postData.collectDeptName = depts[0].text;
    },
    onChangeUser() {
      let id = this.postData.collectUseId;
      let users = this.users.filter(item => {
        return item.id === id; 
      });
      this.postData.collectUseName = users[0].text;
    },
    _getDepartments() {
      getDepartments().then(res => {
        res.forEach(item => {
          this.collectDepts.push({
            id: item.id + "",
            text: item.departmentName
          });
        });
      });
    },
    _getCollectUses() {
      getCollectUses().then(res => {
        res.content.forEach(item => {
          this.users.push({
            id: item.id + "",
            text: item.nickName
          });
        });
      });
    },
  }
}
</script>

<style>
.import-delivery {
  font-size: 14px;
}

.import-delivery .el-form-item {
  margin-left: 15px;
  display: flex;
}

.import-delivery .upload-hint {
  color: #ff8432;
  font-size: 14px;
}

.import-delivery .dialog-footer {
  text-align: center;
}

.import-delivery .el-upload-dragger .el-icon-upload {
  margin: 20px 0 10px;
}

.import-delivery .el-upload-dragger .el-button {
  margin-top: 5px;
}

.import-delivery .el-link {
  border: 1px solid #DCDFE6;
  background: #fff;
  padding: 0 15px;
  font-size: 12px;
}

.import-delivery .label {
  text-align: right;
  line-height: 8px;
  font-size: 13px;
  display: block;
  color: #999;
}

.import-delivery .el-row.tip {
  font-size: 12px;
  color: #999;
}

.import-delivery .el-row.button {
  margin-top: 10px;
}

.import-delivery .el-row.form-items .el-col {
  padding-right: 10px;
}

.import-delivery .el-form-item.line {
  border-bottom: 1px solid #DEDEDE;
  padding-bottom: 18px;
}

.import-delivery .import-label .tip {
  text-align: center;
  line-height: 10px;
  font-size: 12px;
  display: block;
  color: #999;
}
</style>